import React, { PropTypes, Component } from 'react'
import {AtomicBlockUtils, Editor, EditorState, Modifier, Entity, RichUtils, convertToRaw} from 'draft-js'
import './../css/RichText.css'


class RichText extends Component{

	constructor(props){
		super(props);
		this.state = { 
        editorState: EditorState.createEmpty() ,
        showURLInput: false,
        url: '',
        urlType: ''
    };

		this.focus = () => this.refs.editor.focus();

		this.onChange = (editorState) => {
        this.setState({editorState});
        this.props.handlePostRich(editorState.getCurrentContent());
    };

		this.handleKeyCommand = (command) => this._handleKeyCommand(command);
		this.onTab = (e) => this._onTab(e);
		this.toggleBlockType = (type) => this._toggleBlockType(type);
		this.toggleInlineStyle = (style) => this._toggleInlineStyle(style);
		this.toggleColor = (toggledColor) => this._toggleColor(toggledColor);

    this.logState = () => {
      const content = this.state.editorState.getCurrentContent();
      console.log(convertToRaw(content));
    };

    this.onURLChange = (e) => this.setState({urlValue: e.target.value});
    this.addAudio = this._addAudio.bind(this);
    this.addImage = this._addImage.bind(this);
    this.addVideo = this._addVideo.bind(this);
    this.confirmMedia = this._confirmMedia.bind(this);
    this.handleKeyCommand = this._handleKeyCommand.bind(this);
    this.onURLInputKeyDown = this._onURLInputKeyDown.bind(this);

    
      console.warn('++++',this.props.initRich);
    
	}

  componentWillMount() {
    // this.setState({editorState: this.props.initRich});

    // this.state.editorState.getCurrentContent(this.props.initRich);
   
  }

  componentDidMount() {
      console.warn('++++',this.props.initRich);
  }

  _confirmMedia(e) {
    e.preventDefault();
    const {editorState, urlValue, urlType} = this.state;
    const entityKey = Entity.create(urlType, 'IMMUTABLE', {src: urlValue})

    this.setState({
      editorState: AtomicBlockUtils.insertAtomicBlock(
        editorState,
        entityKey,
        ' '
      ),
      showURLInput: false,
      urlValue: '',
    }, () => {
      setTimeout(() => this.focus(), 0);
    });
  }

  _onURLInputKeyDown(e) {
    if (e.which === 13) {
      this._confirmMedia(e);
    }
  }

  _promptForMedia(type) {
    const {editorState} = this.state;
    this.setState({
      showURLInput: true,
      urlValue: '',
      urlType: type,
    }, () => {
      setTimeout(() => this.refs.url.focus(), 0);
    });
  }

  _addAudio() {
    this._promptForMedia('audio');
  }

  _addImage() {
    this._promptForMedia('image');
  }

  _addVideo() {
    this._promptForMedia('video');
  }

	_handleKeyCommand(command) {
	  const {editorState} = this.state;
	  const newState = RichUtils.handleKeyCommand(editorState, command);
	  if (newState) {
	    this.onChange(newState);
	    return true;
	  }
	  return false;
	}

	_onTab(e) {
	  const maxDepth = 4;
	  this.onChange(RichUtils.onTab(e, this.state.editorState, maxDepth));
	}

	_toggleColor(toggledColor) {
	  const {editorState} = this.state;
	  const selection = editorState.getSelection();

	  // Let's just allow one color at a time. Turn off all active colors.
	  const nextContentState = Object.keys(colorStyleMap)
	    .reduce((contentState, color) => {
	      return Modifier.removeInlineStyle(contentState, selection, color)
	    }, editorState.getCurrentContent());

	  let nextEditorState = EditorState.push(
	    editorState,
	    nextContentState,
	    'change-inline-style'
	  );

	  const currentStyle = editorState.getCurrentInlineStyle();

	  // Unset style override for current color.
	  if (selection.isCollapsed()) {
	    nextEditorState = currentStyle.reduce((state, color) => {
	      return RichUtils.toggleInlineStyle(state, color);
	    }, nextEditorState);
	  }

	  // If the color is being toggled on, apply it.
	  if (!currentStyle.has(toggledColor)) {
	    nextEditorState = RichUtils.toggleInlineStyle(
	      nextEditorState,
	      toggledColor
	    );
	  }

	  this.onChange(nextEditorState);
	}

	_toggleBlockType(blockType) {
	  this.onChange(
	    RichUtils.toggleBlockType(
	      this.state.editorState,
	      blockType
	    )
	  );
	}

	_toggleInlineStyle(inlineStyle) {
	  this.onChange(
	    RichUtils.toggleInlineStyle(
	      this.state.editorState,
	      inlineStyle
	    )
	  );
	}

	// detailText(editorState){
	// 	this.setState({editorState})
	// }

	render(){
		const {editorState} = this.state;

		// If the user changes block type before entering any text, we can
		// either style the placeholder or hide it. Let's just hide it now.
		let className = 'RichEditor-editor';
		var contentState = editorState.getCurrentContent();
		if (!contentState.hasText()) {
		  if (contentState.getBlockMap().first().getType() !== 'unstyled') {
		    className += ' RichEditor-hidePlaceholder';
		  }
		}

    let urlInput;
    if (this.state.showURLInput) {
      urlInput =
        <div style={styles.urlInputContainer}>
          <input
            className="main_input"
            onChange={this.onURLChange}
            ref="url"
            style={styles.urlInput}
            type="text"
            value={this.state.urlValue}
            placeholder="请输入图片的路径..."
            onKeyDown={this.onURLInputKeyDown}
          />
          <button  className="main_btn" onMouseDown={this.confirmMedia}>
            确定
          </button>
        </div>;
    }


		return (
			<div className="RichEditor-root">
			  <BlockStyleControls
			    editorState={editorState}
			    onToggle={this.toggleBlockType}
			  />
			  <InlineStyleControls className="inlineFloatLeft"
			    editorState={editorState}
			    onToggle={this.toggleInlineStyle} 
			  />
			  <ColorControls
			    editorState={editorState}
			    onToggle={this.toggleColor} 
			  />
        <div style={styles.buttons}>
          <button className="main_btn" onMouseDown={this.addImage} style={{marginRight: 10}}>
            图片
          </button>
        </div>
        {urlInput}
			  <div className={className} onClick={this.focus}>
			    <Editor
			      blockStyleFn={getBlockStyle}
            blockRendererFn={mediaBlockRenderer}
            customStyleMap={styleMap}
			      editorState={editorState}
			      handleKeyCommand={this.handleKeyCommand}
			      onChange={this.onChange}
			      onTab={this.onTab}
			      ref="editor"

			    />
			  </div>
        <div>{JSON.stringify(editorState.getCurrentContent())}</div>
			</div>
		)
	}

}


const styleMap = {
  CODE: {
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace',
    fontSize: 16,
    padding: 2,
  },
  red: {
    color: 'rgba(255, 0, 0, 1.0)',
  },
  orange: {
    color: 'rgba(255, 127, 0, 1.0)',
  },
  yellow: {
    color: 'rgba(180, 180, 0, 1.0)',
  },
  green: {
    color: 'rgba(0, 180, 0, 1.0)',
  },
  blue: {
    color: 'rgba(0, 0, 255, 1.0)',
  },
  indigo: {
    color: 'rgba(75, 0, 130, 1.0)',
  },
  violet: {
    color: 'rgba(127, 0, 255, 1.0)',
  },
};

function getBlockStyle(block) {
  switch (block.getType()) {
    case 'blockquote': return 'RichEditor-blockquote';
    default: return null;
  }
}

class StyleButton extends Component {
  constructor() {
    super();
    this.onToggle = (e) => {
      e.preventDefault();
      this.props.onToggle(this.props.style);
    };
  }

  render() {
  	// let style;
    let className = 'RichEditor-styleButton';
    if (this.props.active) {
      className += ' RichEditor-activeButton';
      // style = {...styles.styleButton, ...colorStyleMap[this.props.style]};
    }else {
      // style = styles.styleButton;
    }

    return (
      <span className={className} onMouseDown={this.onToggle}>
        {this.props.label}
      </span>
    );
  }
}

// class StyleButton extends React.Component {
//   constructor(props) {
//     super(props);
//     this.onToggle = (e) => {
//       e.preventDefault();
//       this.props.onToggle(this.props.style);
//     };
//   }

//   render() {
//     let style;
//     if (this.props.active) {
//       style = {...styles.styleButton, ...colorStyleMap[this.props.style]};
//     } else {
//       style = styles.styleButton;
//     }

//     return (
//       <span style={style} onMouseDown={this.onToggle}>
//         {this.props.label}
//       </span>
//     );
//   }
// }

const BLOCK_TYPES = [
  {label: 'H1', style: 'header-one'},
  {label: 'H2', style: 'header-two'},
  {label: 'H3', style: 'header-three'},
  {label: 'H4', style: 'header-four'},
  {label: 'H5', style: 'header-five'},
  {label: 'H6', style: 'header-six'},
  {label: '块引用', style: 'blockquote'},
  {label: '有序列表', style: 'unordered-list-item'},
  {label: '无序列表', style: 'ordered-list-item'},
  {label: '代码片段', style: 'code-block'},
];

const BlockStyleControls = (props) => {
  const {editorState} = props;
  const selection = editorState.getSelection();
  const blockType = editorState
    .getCurrentContent()
    .getBlockForKey(selection.getStartKey())
    .getType();

  return (
    <div className="RichEditor-controls">
      {BLOCK_TYPES.map((type) =>
        <StyleButton
          key={type.label}
          active={type.style === blockType}
          label={type.label}
          onToggle={props.onToggle}
          style={type.style}
        />
      )}
    </div>
  );
};

var INLINE_STYLES = [
  {label: '加粗', style: 'BOLD'},
  {label: '斜体', style: 'ITALIC'},
  {label: '下划线', style: 'UNDERLINE'},
  {label: '标记', style: 'CODE'},
];

const InlineStyleControls = (props) => {
  var currentStyle = props.editorState.getCurrentInlineStyle();
  return (
    <div className="RichEditor-controls inlineFloatLeft">
      {INLINE_STYLES.map(type =>
        <StyleButton
          key={type.label}
          active={currentStyle.has(type.style)}
          label={type.label}
          onToggle={props.onToggle}
          style={type.style}
        />
      )}
    </div>
  );
};

var COLORS = [
  {label: '红', style: 'red'},
  {label: '橙', style: 'orange'},
  {label: '黄', style: 'yellow'},
  {label: '绿', style: 'green'},
  {label: '蓝', style: 'blue'},
  {label: '靛', style: 'indigo'},
  {label: '紫', style: 'violet'},
];

const ColorControls = (props) => {
  var currentStyle = props.editorState.getCurrentInlineStyle();
  return (
    <div style={styles.controls}>
      {COLORS.map(type =>
        <StyleButton
          active={currentStyle.has(type.style)}
          label={type.label}
          onToggle={props.onToggle}
          style={type.style}
        />
      )}
    </div>
  );
};

// This object provides the styling information for our custom color
// styles.
const colorStyleMap = {
  red: {
    color: 'rgba(255, 0, 0, 1.0)',
  },
  orange: {
    color: 'rgba(255, 127, 0, 1.0)',
  },
  yellow: {
    color: 'rgba(180, 180, 0, 1.0)',
  },
  green: {
    color: 'rgba(0, 180, 0, 1.0)',
  },
  blue: {
    color: 'rgba(0, 0, 255, 1.0)',
  },
  indigo: {
    color: 'rgba(75, 0, 130, 1.0)',
  },
  violet: {
    color: 'rgba(127, 0, 255, 1.0)',
  },
};

function mediaBlockRenderer(block) {
  if (block.getType() === 'atomic') {
    return {
      component: Media,
      editable: false,
    };
  }

  return null;
}

const Audio = (props) => {
  return <audio controls src={props.src} style={styles.media} />;
};

const Image = (props) => {
  return <img src={props.src} style={styles.media} />;
};

const Video = (props) => {
  return <video controls src={props.src} style={styles.media} />;
};

const Media = (props) => {
  const entity = Entity.get(props.block.getEntityAt(0));
  const {src} = entity.getData();
  const type = entity.getType();

  let media;
  if (type === 'audio') {
    media = <Audio src={src} />;
  } else if (type === 'image') {
    media = <Image src={src} />;
  } else if (type === 'video') {
    media = <Video src={src} />;
  }

  return media;
};

const styles = {
  root: {
    fontFamily: '\'Georgia\', serif',
    fontSize: 14,
    padding: 20,
    width: 600,
  },
  editor: {
    borderTop: '1px solid #ddd',
    cursor: 'text',
    fontSize: 16,
    marginTop: 20,
    minHeight: 400,
    paddingTop: 20,
  },
  controls: {
    fontFamily: '\'Helvetica\', sans-serif',
    fontSize: 14,
    marginBottom: 10,
    userSelect: 'none',
  },
  styleButton: {
    color: '#999',
    cursor: 'pointer',
    marginRight: 16,
    padding: '2px 0',
  },
  buttons: {
    marginBottom: 10,
  },
  urlInputContainer: {
    marginBottom: 10,
  },
  urlInput: {
    fontFamily: '\'Georgia\', serif',
    marginRight: 10,
    padding: 3,
  },
  button: {
    marginTop: 10,
    textAlign: 'center',
  },
  media: {
    width: '100%',
  },
};

export default RichText